<!--
 * @Author: Pure <305737824@qq.com>
 * @CreateTime: 2022-01-17 15:39:42
 * @LastEditors: Pure <305737824@qq.com>
 * @LastEditTime: 2022-03-11 14:27:40
 * @Description: 工单-服务台
-->
<template>
  <el-container class="ticket">
    <el-main>
      <pure-table
        ref="pureTable"
        :columns="filteredColumns"
        :query-condition="queryCondition"
        :list-api="listApi"
      >
        <template slot="header">
          <pure-collapse-transition
            @transition-end="onFlowChartPanelTransitionEnd"
          >
            <flow-chart-panel
              v-show="flowChartVisiable"
              class="flow-chart-panel"
              :red-data="redData"
              @templateTypeChange="onTemplateTypeChange"
            />
          </pure-collapse-transition>
          <el-row
            type="flex"
            align="middle"
            class="base-margin-left base-margin-top"
          >
            <el-col :span="1">
              <caret-button
                label="筛选"
                class="base-margin-right"
                @click="onChangeFlowChartPanelVisiable"
              />
            </el-col>
            <el-col :span="4">
              <retrieval class="base-margin-right" @change="onRetrievalChange" />
            </el-col>
            <el-col :span="15">
              <span
                class="agent base-margin-right"
              ><span>当前坐席类型：</span> 人工坐席</span>
              <span
                class="agent base-margin-right"
              ><span>坐席人员:</span> {{ onlineList }}</span>
            </el-col>
            <el-col :span="4" :offset="1" class="align-right base-margin-right">
              <pure-button label="坐席设定" type="wire-frame" @click="onSetSeat" />
              <pure-button label="创建工单" type="default" @click="onCreateTicket()" />
            </el-col>
          </el-row>
        </template>
        <template slot="indexColumn" slot-scope="scope">
          <el-popover
            v-if="scope.column.fixed"
            style="padding:0"
            popper-class="no-padding"
            placement="bottom-start"
            width="400"
            :offset="-16"
            :visible-arrow="false"
            trigger="click"
          >
            <el-tabs v-model="activedTab" type="border-card">
              <el-tab-pane label="表头设置" name="tableColumn">
                <pure-draggable :data="columns" :has-checked="true" @change="onTableColumnChange" />
              </el-tab-pane>
              <el-tab-pane v-if="tableColumnType==='ticket'" label="排序规则" name="ticketRule">
                <pure-draggable :data="ticketRule" @change="onTicketRuleChange" />
              </el-tab-pane>
            </el-tabs>
            <i slot="reference" class="el-icon-s-operation" />
          </el-popover>
          序号
        </template>
        <template slot="columns" slot-scope="{row,prop}">
          <div v-if="prop ==='recording'">
            <my-audio
              v-if="row.recording"
              :key="row.recording"
              :the-url="row.recording"
            />
            <span v-else>无录音信息</span>
          </div>
          <span v-else-if="prop === 'type'" :class="'call-type--'+row.type">
            {{ row[prop] | phoneState }}
          </span>
          <div v-else-if="prop === 'linkedType'">
            <pure-button
              v-if="row[prop]"
              type="text"
              :label="convertLinkedLabel(row[prop])"
              @click="onViewTicket(row.linkedCode)"
            />
          </div>
          <span v-else-if="prop ==='source'">
            {{ row[prop] | source }}
          </span>
          <span v-else-if="prop ==='degree'" :class="'degree--'+row.degree">
            {{ row[prop] | degree }}
          </span>
          <span v-else-if="prop==='dealType'">
            {{ row[prop] | callRecordDealType }}
          </span>
          <span v-else-if="prop ==='rangeType'">
            {{ row[prop] | range }}
          </span>
          <span v-else-if="prop ==='currState'" :class="'state--'+row.currState">
            {{ row[prop] | ticketState }}
          </span>
          <span v-else-if="prop==='faultRemark'">
            <linked-button
              v-if="row.hurryCount"
              :type="1"
              :count="row.hurryCount"
              @click="onViewLinkedCallRecord(row, 1)"
            />
            <linked-button
              v-if="row.repeatCount"
              :count="row.repeatCount"
              :type="2"
              @click="onViewLinkedCallRecord(row,2)"
            />
            <linked-button
              v-if="row.revokeCount"
              :count="row.revokeCount"
              :type="3"
              @click="onViewLinkedCallRecord(row,3)"
            />
            <el-tooltip content="点击查看主工单" placement="top">
              <pure-tag
                v-if="row['orderNum'].includes('#')"
                :label="'协'"
                @click="onViewTicket(row.parentOrderNum)"
              />
            </el-tooltip>
            {{ row[prop] }}
          </span>
          <span v-else>
            {{ row[prop] }}
          </span>
        </template>
        <template v-if="tableColumnType!=='callRecordPhoneFind'" :slot="tableColumnType==='callRecordPhoneFind'?'':'operationColumn'" slot-scope="{row}">
          <template v-if="tableColumnType === 'callRecord'">
            <pure-button
              v-if="row.type===0&&!row.dealType"
              type="text"
              label="建单"
              @click="onCreateTicket('byCallRecord',row)"
            />
            <pure-button
              v-if="row.type===0&&!row.dealType"
              type="text"
              label="电话找人"
              @click="onFindPerson(row.id)"
            />
            <pure-button
              v-if="row.type===2&&!row.dealType"
              type="text"
              label="无效电话"
              @click="onInvalidPhone(row.id)"
            />
            <pure-button
              v-if="['end_phone','create_order'].includes(row.dealType)"
              type="text"
              label="查看"
              @click="onViewTicket(row.orderNum)"
            />
          </template>

          <template v-else>
            <pure-button
              v-if="canDistributState.includes(row['currState'])"
              type="text"
              label="派单"
              @click="onDispatchTicket(row.orderNum)"
            />
            <pure-button
              v-if="canEndState.includes(row['currState'])"
              type="text"
              label="终止"
              @click="onUpdateTicket(row.orderNum, 'endTermination')"
            />
            <pure-button
              v-if="
                canSuspendState.includes(
                  row['currState']
                )
              "
              type="text"
              label="暂停"
              @click="onUpdateTicket(row.orderNum, 'suspend')"
            />
            <pure-button
              type="text"
              label="查看"
              @click="onViewTicket(row.orderNum)"
            />
            <pure-button
              v-if="canOpenState.includes(row['currState'])"
              type="text"
              label="开启"
              @click="onOpenSuspendedTicket(row.orderNum)"
            />

            <pure-button
              v-if="canRestartState.includes(row['currState'])"
              type="text"
              label="重启"
              @click="onRestartTerminatedTicket(row.orderNum)"
            />
          </template>
        </template>
      </pure-table>
    </el-main>
    <un-received />
  </el-container>
</template>

<script>
import ServiceDeskApi from './api';
import TicketMixin from '../mixin';
import FlowChartPanel from './panel/flowChart.vue';
import SeatSettingDialog from './dialog/seatSetting.vue';
import {
  ticketState,
  callRecordDealType,
} from '../filter';
import PureTable from '@/feat/component/pureTable';
import CaretButton from '@/components/button/caretButton';
import PureCollapseTransition from '@/components/collapseTransition';
import PureWebsocket from '@/utils/PureWebSocket';
import MyAudio from '@/components/audio/audio';
import FindPersonByPhone from '@/views/reportFault/sharedComponents/dialog/findPersonByPhone';
import LinkedButton from '@/views/reportFault/sharedComponents/linkedButton';
import UnReceived from '@/views/reportFault/sharedComponents/panel/unReceived.vue';
import PureTag from '@/components/tag/tag.vue';
import PureDraggable from '@/components/draggable';
import {
  findIndex,
} from 'lodash';
import {
  mapGetters,
} from 'vuex';
export default {
  name: 'BzFwt',
  components: {
    PureTable,
    FlowChartPanel,
    CaretButton,
    PureCollapseTransition,
    MyAudio,
    LinkedButton,
    UnReceived,
    PureTag,
    PureDraggable,
  },
  filters: {
    ticketState,
    callRecordDealType,
  },
  mixins: [TicketMixin],
  data() {
    return {
      columns: [],
      // 表头类型 ticket/callRecord/callRecordPhoneFind(电话找人)
      tableColumnType: 'ticket',
      listApi: ServiceDeskApi.list,
      flowChartVisiable: true,
      activedTab: 'tableColumn',
      // 红点数据
      redData: {},
      queryCondition: {
        query: null,
        temp: 'waitDelivery',
        sortTemp: null,
      },
      ticketRule: this.$store.state.ticketServiceDesk.ticketRule,

      // 可执行派单操作的工单状态
      canDistributState: ['wait_delivery'],
      // 可执行终止操作的工单状态
      canEndState: [
        'processing',
        'suspended'
      ],
      // 可执行暂停操作的工单状态
      canSuspendState: [
        'processing'
      ],

      // 可执行重启操作状态 -
      canRestartState: ['terminated'],
      // 可执行开启操作状态
      canOpenState: ['suspended'],
    };
  },

  computed: {
    ...mapGetters(['userInfo', 'onlineList']),
    callRecordTableColumn() {
      return this.$store.state.ticketServiceDesk.callRecordTableColumn;
    },
    callRecordPhoneFindTableColumn() {
      return this.$store.state.ticketServiceDesk.callRecordPhoneFindTableColumn;
    },
    ticketTableColumn() {
      return this.$store.state.ticketServiceDesk.ticketTableColumn;
    },
    filteredColumns() {
      return this.columns.filter(item => item.checked).map(item => {
        return item;
      });
    },
  },
  async mounted() {
    this.$refs.pureTable.afterFetchData = this.afterFetchData;
    this.$store.state.ticketServiceDesk.ws = new PureWebsocket({
      url: `${this.$store.state.login.uriConfig.wsUri}?token=${this.$store.state.login.refreshToken}`,
    });
    this.$store.state.ticketServiceDesk.ws.onMessage(async (data) => {
      if (data.code === 0) {
        console.log('websocket开始监听');
      } else if (data.code === 10) {
        console.log('当前在线坐席：', data.body);
        const phone = await this.$store.dispatch('ticketServiceDesk/INIT_ONLINE_INFO', data.body);
        this.$store.state.ticketServiceDesk.ws.send({ code: 16, data: phone, });
      } else if (data.code === 12) {
        console.log('你好，有弹屏信息');

        if (this.$store.state.app.openedDrawerOrDialogCount > 0) {
          this.$store.state.app.unrecivedPanelVisible = true;
          this.$store.state.app.unrevivedData.push({ orign: { info: data.body, }, phone: data.body.phone, user: data.body.user, deptId: data.body.deptId, time: data.body.createTime, id: data.body.id, });
        } else {
          this.onCreateTicket('byPop', data.body);
        }
      } else if (data.code === 11) {
        console.log('坐席变更', data.body);
        this.$store.dispatch('ticketServiceDesk/UPDATE_ONLINE_INFO', data.body);
      } else if (data.code === 14) {
        console.log('电话挂断');
        const index = findIndex(this.$store.state.app.unrevivedData, (item) => item.id === data.body.id);
        if (index >= 0) {
          this.$store.state.app.unrevivedData.splice(index, 1);
        }
      }
    });
  },

  async created() {
    try {
      this.sortTemp = this.genSortTemp(this.ticketRule);
      this.queryCondition.sortTemp = this.genSortTemp(this.ticketRule);
      this.columns = this.ticketTableColumn;
    } catch (error) {
      console.log(error);
    }
  },

  methods: {
    onFlowChartPanelTransitionEnd() {
      setTimeout(() => {
        this.$refs.pureTable.setTableMaxHeight();
      }, 100);
    },
    onTemplateTypeChange(type) {
      // 属于通话记录的模板
      // 电话报修-phoneCreate
      // 已接-pickedUp
      // 未接-missed
      // 待建单-untenited
      // 电话找人-findSomeone 与普通通话记录表头不一样
      const callRecordTemplate = ['phoneCreate', 'pickedUp', 'missed', 'untenited'];
      this.$refs.pureTable.currentPage = 0;
      if (callRecordTemplate.includes(type)) {
        this.tableColumnType = 'callRecord';
        this.columns = this.callRecordTableColumn;
        this.listApi = ServiceDeskApi.callRecordList;
      } else if (type === 'findSomeone') {
        this.tableColumnType = 'callRecordPhoneFind';
        this.columns = this.callRecordPhoneFindTableColumn;
        this.listApi = ServiceDeskApi.callRecordList;
      } else {
        this.tableColumnType = 'ticket';
        this.columns = this.ticketTableColumn;
        this.listApi = ServiceDeskApi.list;
      }
      this.queryCondition.temp = type;
      this.activedTab = 'tableColumn';
    },
    onChangeFlowChartPanelVisiable() {
      this.flowChartVisiable = !this.flowChartVisiable;
    },
    onRetrievalChange(val) {
      this.queryCondition.query = val;
    },
    onSetSeat() {
      this.$dialog({
        title: '坐席设定',
        width: '688px',
        top: '32vh',
        position: 'center',
        component: () => <SeatSettingDialog/>,
      });
    },

    // 生成排序规则字符串
    genSortTemp(ticketRule) {
      return ticketRule.map(item => item.label).join(',') || null;
    },
    convertLinkedLabel(linkedType) {
      switch (linkedType) {
        case 1:
          return '催单';
        case 2:
          return '重报';
        case 3:
          return '撤单';
        default:
          return null;
      }
    },
    // 表头设置变更
    async onTableColumnChange(newVal) {
      this.columns = newVal;
      if (this.tableColumnType === 'callRecord') {
        this.$store.dispatch('ticketServiceDesk/UPDATE_CALL_RECORD_COLUMN', newVal);
      } else {
        this.$store.dispatch('ticketServiceDesk/UPDATE_TICKET_TABLE_COLUMN', newVal);
      }
    },
    // 排序规则变更
    async onTicketRuleChange(newTicketRule) {
      this.ticketRule = newTicketRule;
      this.sortTemp = this.genSortTemp(newTicketRule);
      this.onPerformedOpertion();
      this.$store.dispatch('ticketServiceDesk/UPDATE_TICKET_RULE', newTicketRule);
    },
    onPhoneFindPerson(row) {
      this.$dialog({
        title: '电话找人',
        width: '390px',
        top: '32vh',
        position: 'center',
        component: () => <FindPersonByPhone orderId={row.id} onDone={this.onPerformedOpertion}/>,
      });
    },
    async afterFetchData() {
      const rs = await ServiceDeskApi.redInfo();
      this.redData = Object.assign({}, this.redData, rs);
    },
    onPerformedOpertion() {
      this.$refs.pureTable.fetchData();
      this.afterFetchData();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/ticket.scss";
.flow-chart-panel {
  width: 1040px;
  height: 179px;
  overflow-y: hidden;
}
.agent {
  color: #2d405e;
  font-size: $--pure-base-font-size;
  span {
    color: #879bba;
  }
}
</style>
